package net.lainiao.morethread.Chapter3.demo6;

import java.util.Date;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2017/3/2.
 */
public class Student implements Runnable {
    private Phaser phaser;

    public Student(Phaser phaser) {
        this.phaser = phaser;
    }

    @Override
    public void run() {
        String threadName=Thread.currentThread().getName();

        System.out.println(threadName+" Has arrived to do the exam");
        phaser.arriveAndAwaitAdvance();

        System.out.println(threadName+"Is going to do the first exerciese" +(new Date()));
        doExercise1();
        System.out.println(threadName+"Has done the first exerice   "+(new Date()));
        phaser.arriveAndAwaitAdvance();

        System.out.println(threadName+"Is going to do the Second exerciese" +(new Date()));
        doExercise2();
        System.out.println(threadName+"Has done the Second exerice   "+(new Date()));
        phaser.arriveAndAwaitAdvance();


        System.out.println(threadName+"Is going to do the Third exerciese" +(new Date()));
        doExercise3();
        System.out.println(threadName+"Has done the Third exerice   "+(new Date()));
        phaser.arriveAndAwaitAdvance();


    }

    private void doExercise3() {
        long duration=(long)(Math.random()*10);
        try {
            TimeUnit.SECONDS.sleep(duration);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void doExercise2() {
        long duration=(long)(Math.random()*10);
        try {
            TimeUnit.SECONDS.sleep(duration);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void doExercise1() {
        long duration=(long)(Math.random()*10);
        try {
            TimeUnit.SECONDS.sleep(duration);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
